package com.lianmai.chaincard;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.notification.BasicCustomPushNotification;
import com.alibaba.sdk.android.push.notification.CustomNotificationBuilder;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.lianmai.chaincard.widget.GlideImageLoader;
import com.lianmai.chaincard.widget.OKHttpEngine;
import com.tencent.smtt.sdk.QbSdk;
import com.youth.xframe.XFrame;
import com.youth.xframe.base.XApplication;
import com.youth.xframe.utils.imageload.ImageLoader;
import com.youth.xframe.utils.log.XLog;

import org.bining.footstone.App;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.SharedUtils;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import butterknife.ButterKnife;

/**
 * 创建日期：2018/8/15 0015
 * 作者:Kite
 * llllll                                     kkkkkkk
 * l::::l                                     k:::::k
 * l::::l                                     k:::::k
 * l::::l                                     k:::::k
 * l::::l uuuuuu    uuuuuu     ooooooooooo    k:::::k    kkkkkkkuuuuuu    uuuuuunnnn  nnnnnnnn
 * l::::l u::::u    u::::u   oo:::::::::::oo  k:::::k   k:::::k u::::u    u::::un:::nn::::::::nn
 * l::::l u::::u    u::::u  o:::::::::::::::o k:::::k  k:::::k  u::::u    u::::un::::::::::::::nn
 * l::::l u::::u    u::::u  o:::::ooooo:::::o k:::::k k:::::k   u::::u    u::::unn:::::::::::::::n
 * l::::l u::::u    u::::u  o::::o     o::::o k::::::k:::::k    u::::u    u::::u  n:::::nnnn:::::n
 * l::::l u::::u    u::::u  o::::o     o::::o k:::::::::::k     u::::u    u::::u  n::::n    n::::n
 * l::::l u::::u    u::::u  o::::o     o::::o k:::::::::::k     u::::u    u::::u  n::::n    n::::n
 * l::::l u:::::uuuu:::::u  o::::o     o::::o k::::::k:::::k    u:::::uuuu:::::u  n::::n    n::::n
 * l::::::lu:::::::::::::::uuo:::::ooooo:::::ok::::::k k:::::k   u:::::::::::::::uun::::n    n::::n
 * l::::::l u:::::::::::::::uo:::::::::::::::ok::::::k  k:::::k   u:::::::::::::::un::::n    n::::n
 * l::::::l  uu::::::::uu:::u oo:::::::::::oo k::::::k   k:::::k   uu::::::::uu:::un::::n    n::::n
 * llllllll    uuuuuuuu  uuuu   ooooooooooo   kkkkkkkk    kkkkkkk    uuuuuuuu  uuuunnnnnn    nnnnnn
 */
public class MyApplication extends XApplication {

    private static MyApplication mLMApplication;

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;

    public static MyApplication getInstance() {
        return mLMApplication;
    }

    /**
     * 二维码下载
     */
    public static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "chain thread #" + mCount.getAndIncrement());
        }
    });

    @Override
    public void onCreate() {
        super.onCreate();
        XFrame.init(this);
        mLMApplication = this;
        XFrame.initXImageLoader(new GlideImageLoader(mLMApplication));//图片请求框架
        XFrame.initXHttp(new OKHttpEngine());//网络请求框架
        App.init(mLMApplication);//FileUtils的初始化
        initLocation();
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                XLog.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);

    }

    /**
     * 初始化云推送通道
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        SharedUtils.put(Constants.USERDEVICEID, PushServiceFactory.getCloudPushService().getDeviceId());
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                XLog.d("阿里云推送初始化成功:" + PushServiceFactory.getCloudPushService().getDeviceId());
                SharedUtils.put(Constants.USERDEVICEID, PushServiceFactory.getCloudPushService().getDeviceId());

                initLocation();

                String openId = SharedUtils.getString(Constants.USEROPENID);
                if (!TextUtils.isEmpty(openId)) {
                    PushServiceFactory.getCloudPushService().bindAccount(openId, new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            XLog.d("阿里云推送绑定账号成功");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            XLog.d("阿里云推送绑定账号失败");
                        }
                    });
                }
                // PushServiceFactory.getCloudPushService().

                boolean isMessageNotice = SharedUtils.getBoolean(Constants.ISMESSAGENOTICE, false);
                boolean isOpenSound = SharedUtils.getBoolean(Constants.ISOPENSUOUND, false);
                boolean isOpenVibration = SharedUtils.getBoolean(Constants.ISOPENVIBRATION, false);

                BasicCustomPushNotification notification = new BasicCustomPushNotification();
                if (isMessageNotice && (isOpenSound || isOpenVibration)) {
                    if (isOpenSound && isOpenVibration) {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_VIBRATE_AND_SOUND);
                    } else if (isOpenSound) {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_SOUND);
                    } else {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_VIBRATE);
                    }
                } else {
                    notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_SILENT);
                }
                CustomNotificationBuilder.getInstance().setCustomNotification(1, notification);
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                XLog.d("阿里云推送初始化失败 ErrorCode:" + errorCode + " ErrorMessage:" + errorMessage);
            }
        });
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //异步获取定位结果
        AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //解析定位结果
//                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                        amapLocation.getLatitude();//获取纬度
//                        amapLocation.getLongitude();//获取经度
//                        amapLocation.getAccuracy();//获取精度信息
//                        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                        amapLocation.getCountry();//国家信息
//                        amapLocation.getProvince();//省信息
//                        amapLocation.getCity();//城市信息
//                        amapLocation.getDistrict();//城区信息
//                        amapLocation.getStreet();//街道信息
//                        amapLocation.getStreetNum();//街道门牌号信息
//                        amapLocation.getCityCode();//城市编码
//                        amapLocation.getAdCode();//地区编码
//                        amapLocation.getAoiName();//获取当前定位点的AOI信息
//                        amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                        amapLocation.getFloor();//获取当前室内定位的楼层
//                        amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                        //获取定位时间
//                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Date date = new Date(amapLocation.getTime());
//                        df.format(date);
                        mLocationClient.stopLocation();

                        XLog.e("Location>> 纬度:" + amapLocation.getLatitude() + " 经度:" + amapLocation.getLongitude() + " Address:" + amapLocation.getAddress());

                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        XLog.e("AmapError" + "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        //启动定位
        mLocationClient.startLocation();
    }

}
